package com.playwright.util.zhihu2toutiao;

import com.microsoft.playwright.*;
import com.microsoft.playwright.options.LoadState;

import java.nio.file.Paths;
import java.util.List;

/**
 * @author liyanhao
 * @Date 2024-01-17 11:48
 */
public class YiYanUtils {
    private static String defaultPath = "_8106-playwright\\src\\main\\java\\com\\playwright\\auth\\baidu_YiYan_state.json";

    public static void main(String[] args) throws InterruptedException {
//        String score = getAnswer("汉朝皇帝排名");
//        System.out.println(score);
    }


    public static void saveAuthYiYan(Page page) {
        page.navigate("https://yiyan.baidu.com/");
        page.waitForLoadState(LoadState.DOMCONTENTLOADED); // 等待页面完全加载
        String statePath = Paths.get(defaultPath).toAbsolutePath().toString();
        try {
            Thread.sleep(30000l);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        BrowserContext.StorageStateOptions options = new BrowserContext.StorageStateOptions();
        options.setPath(Paths.get(statePath));
    }

    /**
     * 携带登录信息获取浏览器
     *
     * @param playwright
     * @return
     */
    public static BrowserContext getBrowserContext(Page page) {
        boolean login = isLogin(page);
        //未登录 登录一下
        if (!login) {
            saveAuthYiYan(page);
        }
        return getContext();
    }

    /**
     * 判断是否登录 登录true 未登录 false
     *
     * @return
     * @throws InterruptedException
     */
    private static boolean isLogin(Page page) {
        page.navigate("https://yiyan.baidu.com/");
        Locator locator = page.getByText("开始体验");
        return !locator.isVisible();
    }


    private static BrowserContext getContext() {
        Browser browser = PlaywrightUtils.getBrowser(Playwright.create());
        // 3. 保存认证后的浏览器状态
        String statePath = Paths.get(defaultPath).toAbsolutePath().toString();
        BrowserContext.StorageStateOptions options = new BrowserContext.StorageStateOptions();
        options.setPath(Paths.get(statePath));
        // 加载之前保存的浏览器状态以保持登录状态
        BrowserContext context = browser.newContext(new Browser.NewContextOptions().setStorageStatePath(Paths.get(statePath)));
        return context;
    }

    public static String getAnswer(String question) {
        BrowserContext browserContext = YiYanUtils.getBrowserContext(getContext().newPage());
        Page page = browserContext.newPage();
        page.navigate("https://yiyan.baidu.com/");
        page.getByPlaceholder("请输入问题或“/”获取收藏指令，可通过shift+回车换行").click();
        page.getByPlaceholder("请输入问题或“/”获取收藏指令，可通过shift+回车换行").fill(question);
        page.getByPlaceholder("请输入问题或“/”获取收藏指令，可通过shift+回车换行").press("Enter");
        page.waitForSelector(".yyjIo3Fm");
        List<ElementHandle> similarElements = page.querySelectorAll(".custom-html");

        return similarElements.get(0).textContent();
    }


}
